<template>
    <div ref="apiParamsRef">
        <zh-row>
            <zh-col :span="6">
                <zh-card shadow="hover">
                    <div>
                        <zh-tree
                                ref="apiTreeRef"
                                funcCode="APIPARAMS0007"
                                :queryParam="paramsInfo"
                                :expand-on-click-node="false"
                                :lazy="false"
                                node-key="paramKey"
                                :height="isTagsview ? `calc(100vh - 142px)` : `calc(100vh - 108px)`"
                                :draggable="true"
                                :props="{ label: 'title' }"
                                @node-click="onNodeClick"
                        ></zh-tree>
                    </div>
                </zh-card>
            </zh-col>
        <zh-col :span="18">
        <zh-form ref="apiParamsForm" :md="12" :lg="12" :xl="12" style="margin-top: 20px" :model="item" :rules="rules">
                <zh-form-input
                    v-if="item.paramId!=''"
                    prop="pararmId"
                    label="参数id"
                    :disabled="true"
                    v-model="item.paramId"
                ></zh-form-input>
                <zh-form-input prop="paramType" label="参数类型" :disabled="true" v-model="item.paramType"></zh-form-input>
                <zh-form-input :disabled="item.displayFlag" prop="paramField" label="参数字段" placeholder="请输入参数字段" v-model="item.paramField"></zh-form-input>
                <zh-form-input :disabled="item.displayFlag" prop="paramName" label="字段中文" span:6px placeholder="请输入字段中文描述" v-model="item.paramName"></zh-form-input>
                <zh-form-input :disabled="item.displayFlag" prop="paramValue" label="默认值" placeholder="请输入默认值" v-model="item.paramValue"></zh-form-input>
                <zh-form-select
                    :disabled="item.displayFlag"
                    prop="notNull"
                    label="是否必填"
                    placeholder="请选择"
                    :options="[{dictKey:'0',dictValue:'否'},{dictKey:'1',dictValue:'是'}]"
                    v-model="item.notNull"
                ></zh-form-select>
                <zh-form-select :disabled="item.displayFlag" prop="fieldType" label="数据类型" placeholder="请选择" :options="state.dictData.fieldType" v-model="item.fieldType"></zh-form-select>
                <zh-form-select prop="paramFrom" label="参数所属" placeholder="请选择" :disabled="true" :options="state.dictData.paramFrom" v-model="item.paramFrom"></zh-form-select>
                <zh-form-input :disabled="item.displayFlag" prop="arrayTextSplit" label="数组分隔符" placeholder="请输入数组分隔符" v-model="item.arrayTextSplit"></zh-form-input>

                <zh-form-select :disabled="item.displayFlag"  prop="fieldFormat" label="数据格式" placeholder="请选择" :options="state.dictData.fieldFormat" v-model="item.fieldFormat"></zh-form-select>
                <zh-form-input :disabled="item.displayFlag"  prop="textSplit" label="文本分割符" placeholder="请输入文本分割符" v-model="item.textSplit"></zh-form-input>
                <zh-form-input
                    prop="parentId"
                    label="上级目录id"
                    :disabled="true"
                    v-model="item.parentId"
                ></zh-form-input>
                <zh-form-input
                    :disabled="true"
                    :span="24"
                    :rows="10"
                    prop="remarks"
                    type="textarea"
                    label="备注"
                    v-model="jsonParams"
                ></zh-form-input>
        </zh-form>
        </zh-col>
        </zh-row>
    </div>
</template>

<script lang="ts" setup name="apiParamsForm">
    import { ElMessage } from 'element-plus';
    import {FormInstance} from 'element-plus';
    //----------------定义接收参数-------------------------------

    //------------------定义子组件---------------------------
    const {isTagsview} = storeToRefs($store.theme);
    const apiParamsRef = ref<FormInstance>();
    const apiParamsForm = ref();
    const apiTreeRef = ref();
    const selectNode: any = ref(null);
    const saveType = ref('rootAdd');
    let rs =ref<any>({});
    //------------------内部变量定义-------------------------

    const state = reactive({
        dictData: {} as any,
    });

    const rules = reactive({
        paramName: [
            {
                required: true,
                message: '请输入字段中文描述',
                trigger: 'blur',
            },
        ],
       paramField: [
          {
               required: true,
               message: '请输入参数字段',
               trigger: 'blur',
           }
       ],
       fieldType: [
           {
               required: true,
               message: '请选择数据类型',
               trigger: 'blur',
          }
       ],
    });
    const jsonParams = ref();
    const treeData = ref();
    let item = reactive({
        paramId: '',
        functionCode:'',
        paramType:'',
        paramField:'',
        paramName:'',
        paramValue:'',
        notNull:'0',
        fieldType:'',
        paramFrom:'header',
        arrayTextSplit:'',
        fieldFormat:'json',
        textSplit:'',
        parentId:'',
        icon: '',
        nodeType: '1',
        rate: undefined,
        displayFlag:true,
    });
    //取得上级字段
    const selectApi=ref({
        paramId:'',
        parentId:'',
    });

    const props = defineProps({
        paramsInfo: Object,
    });
    //判断有无接口的入参

    //------------------定义调用方法-------------------------

    const onNodeClick = (node) => {
        //点击树节点触发事件
        selectNode.value = node;
        //执行查询paramId
        getApiParamsInfo(node.key);
        saveType.value = 'edit';
        changeActiveName();
    };
    //改变tab调用方法
    const changeActiveName = () => {

    };
    //根目录新增
    const apiRootAdd =() =>{
        resetForm();
        selectNode.value = '';
        item.parentId = '';
        apiTreeRef.value!.setCurrentKey(null, false);
    };
    //同级新增
    const apiEqualAdd = () =>{
        if (selectNode.value) {
            item.paramId='';
            item.paramField='';
            item.paramName='';
            item.paramValue='';
            item.notNull='0';
            item.fieldType='';
            item.arrayTextSplit='';
            item.fieldFormat='';
            item.textSplit='';
            item.parentId=selectApi.value.parentId;
        } else {
            ElMessage({
                message: '请先在左边路由树中选择节点',
                type: 'warning',
            });
        }
    };
    //子级新增
    const childApiAdd = () => {
        if (selectNode.value) {
            item.paramId='';
            item.paramField='';
            item.paramName='';
            item.paramValue='';
            item.notNull='0';
            item.fieldType='';
            item.arrayTextSplit='';
            item.fieldFormat='';
            item.textSplit='';
            item.parentId=selectApi.value.paramId;
        } else {
            ElMessage({
                message: '请先在左边路由树中选择节点',
                type: 'warning',
            });
        }
    };
    //删除路由
    const deleteApi = () => {
        if (selectNode.value) {
            const params = { paramId: selectNode.value.key };
            $api.common.send.post('APIPARAMS0006',params).then(() => {
                ElMessage({
                    message: '删除路由成功',
                    type: 'success',
                });
                apiTreeRef.value.query();
            });
        } else {
            ElMessage({
                message: '请先在左边路由树中选择需要删除的节点',
                type: 'warning',
            });
        }
    };
    //保存按钮函数
    const saveApi = async () => {
        //保存路由信息
        await saveForm();
        let res :any = rs;
        //保存成功
        if (res && res.saveType === 'add') {
          await  apiTreeRef.value.query();
            ElMessage.success('新增成功！');
        } else if (res && res.saveType === 'edit') {
            //更新树节点信息
          await apiTreeRef.value.query();
            ElMessage.success('修改成功！');
        }
       createJson();
        //重置表单
        resetForm();
    };
    //查询
    const getApiParamsInfo = (paramId) => {
        const apiParams = { paramId: paramId };
        $api.common.send.post('APIPARAMS0002',apiParams).then((res) => {
            item = Object.assign(item, res.result || {});
            selectApi.value.paramId = res.result.paramId;
            selectApi.value.parentId = res.result.parentId;
        });
    };

    //保存数据
    const saveForm = async () => {
            //校验表单
            let checkFlag = await apiParamsForm.value.checkForm();
            if (checkFlag) {
                //校验通过
                let saveForm = Object.assign({}, item);
                //保存
                if (!saveForm.paramId) {
                    await $api.common.send.post('APIPARAMS0004', saveForm).then((res) => {
                        rs = res.result;
                        rs.saveType = "add";
                    });
                //修改
                } else {
                    await $api.common.send.post('APIPARAMS0005', saveForm).then((res) => {
                        rs = res.result;
                        rs.saveType = "edit";
                    });
                }
                return null;
            }else{
                //console.log("校验不通过");
            }
    };

    //重置表单
    function resetForm(){
        item.paramId='';
        item.paramField='';
        item.paramName='';
        item.paramValue='';
        item.notNull='0';
        item.fieldType='';
        item.arrayTextSplit='';
        item.fieldFormat='';
        item.textSplit='';
    }
    //------------------初始化------------------------------
    const params = {
        dictFields: 'fieldType,paramFrom,fieldFormat',
    };
    $api.common.getBatchDict.post(params).then((res) => {
        state.dictData = res.result;
    });
    //初始化参数值
    async function initParams (){
        if(props.paramsInfo){
            item.paramFrom = props.paramsInfo.paramFrom;
            item.paramType = props.paramsInfo.paramType;
            item.functionCode = props.paramsInfo.functionCode;
            item.displayFlag = props.paramsInfo.displayFlag;
        }
      jsonParams.value ="{}"
      // await createJson();
      setTimeout(() => {
        createJson();
      },1000)
    }

    const createJson = async()=>{
      treeData.value =await apiTreeRef.value.treeList;
      let data
      if(item.paramFrom==="body"){
        data =transformTree(treeData.value)
        jsonParams.value = JSON.stringify( data, null, 2);

      }else if(item.paramFrom==="header"){
        data =transformTreeToHeaders(treeData.value)
        jsonParams.value = data
      }else if (item.paramFrom==="params"){
        data = flattenTreeToParams(treeData.value)
        jsonParams.value = data
      }
    }

    /**
     * 以json格式输出
     * @param treeData
     */
    function transformTree(treeData) {
      return treeData.reduce((acc, node) => {
        if (node.isLeaf) {
          acc[node.value] = '';
        } else {
          acc[node.value] = transformTree(node.children || []);
        }
        return acc;
      }, {});
    }

    /**
     * 请求头形式输出
     * @param treeData
     */
    function transformTreeToHeaders(treeData) {
      const headers = [];
      function traverse(node) {
        if (node.isLeaf) {
          // 对于叶子节点，直接添加到headers数组中
          headers.push(`${node.value}: " "`);
        } else {
          // 如果有子节点，递归遍历
          node.children.forEach(child => traverse(child));
        }
      }
      treeData.forEach(node => traverse(node));
      return headers;
    }

    /**
     * 请求参数形式输出
     * @param treeData
     */
    const flattenTreeToParams = (treeData) => {
      return treeData.reduce((acc, node) => {
        if (node.isLeaf) {
          return `${acc}&${node.value}=” “`;
        }
        return `${acc}${flattenTreeToParams(node.children || [])}`;
      }, '');
    }


    defineExpose({apiRootAdd,apiEqualAdd,childApiAdd,saveApi,deleteApi,initParams,saveForm,apiParamsRef,item});
</script>
